local Data "merger_data"

noi disp "Obtaining merger data..."
noi disp "Verifying that `Data'.dta does not already exist..."
* This returns an error if the file does not exist.
capture confirm file `Data'.dta

* If an error is returned, then the commands below are run.
if _rc == 601 {
	noi disp "Data not found.  Building data..."
	noi disp "Loading merger_updated.csv..."
	insheet using "$SourceData\mergers.csv", clear
	noi disp "Building merger_data.dta..."
	
	keep cert id closed acquiring failed year_adj stcnty
	
	bysort cert year_adj: egen macquiring = max(acquiring)
	bysort cert year_adj: egen mfailed = max(failed)
	bysort cert year_adj: egen mclosed = max(closed)
	drop closed acquiring id failed
	
	
	* Keep only the first instance
	duplicates drop cert year_adj, force
	
	rename year_adj year
	rename stcnty stcntyHQ
	*The last year of SOD data for a closed institution in year YYYY is YYYY-1
	replace year = year-1
	sort cert year
	compress
	save "$LocalData\\`Data'.dta", replace
	save "$LocalData\Archive\\`Data'`CurrentDate'.dta", replace
}
* This runs if no error was returned.
else noi disp "Data already exists."
noi etime
noi disp " "
